
package com.rt.schedulenew.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rt.schedulebase.dto.*;
import com.rt.schedulebase.entity.DictItemGroup;
import com.rt.schedulebase.entity.DictScheduleRegularDef;
import com.rt.schedulebase.mapper.DictExamItemMapper;
import com.rt.schedulebase.mapper.DictItemGroupMapper;
import com.rt.schedulebase.mapper.DictScheduleRegularDefMapper;
import com.rt.schedulenew.api.*;
import com.rt.schedulenew.utils.base.CommonUtil;
import com.rt.schedulenew.utils.base.ConstantsUtil;
import com.rt.schedulenew.utils.global.JsonResult;
import com.rt.schedulenew.utils.global.JsonResultUtil;
import com.rt.schedulenew.utils.util.DateUtil;
import com.rt.schedulenew.utils.util.EhCacheUtil;
import com.rt.schedulenew.utils.util.JsonUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/***
 * 预约规则定义
 */
@Service
public class DictScheduleRegularDefServiceImpl extends ServiceImpl<DictScheduleRegularDefMapper, DictScheduleRegularDef> implements IDictScheduleRegularDefService {
    @Autowired
    private ICommonService commonService;
    @Autowired
    private IExamSyslogService examSyslogService;
    @Autowired
    private DictExamItemMapper dictExamItemMapper;
    @Autowired
    private CacheServiceImpl cacheServiceImpl;
    @Autowired
    private ConfigServiceImpl configService;
    @Autowired
    private IDictQueueClassService dictQueueClassService;
    @Autowired
    private IDictWardService dictWardService;
    @Autowired
    private IDictDeptService dictDeptService;
    @Autowired
    private IDictPatientSourceService dictPatientSourceService;
    @Autowired
    private DictItemGroupMapper dictItemGroupMapper;
    @Autowired
    private IDictUsersService dictUsersService;
    @Autowired
    private IDictSerialService dictSerialService;

    @Override
    public List<DictScheduleRegularDef> selectList(DictScheduleRegularDefDto dto) {
        QueryWrapper<DictScheduleRegularDef> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(dto.getExamClass())) {
            queryWrapper.in("EXAM_CLASS", CommonUtil.split2List(dto.getExamClass()));
        }
        if (StringUtils.isNotBlank(dto.getRegularModule())) {
            if (ConstantsUtil.RegularModule.REGULAR_SCHEDULE.getKey().equals(dto.getRegularModule())) {
                queryWrapper.ne("REGULAR_TYPE", "3");
            } else if (ConstantsUtil.RegularModule.REGULAR_NUMBER.getKey().equals(dto.getRegularModule())) {
                queryWrapper.eq("REGULAR_TYPE", "3");
            }
        }
        if (StringUtils.isNotBlank(dto.getExamItems())) {
            List<String> examItemList = CommonUtil.split2List(dto.getExamItems());
            for (String examItem : examItemList) {
                queryWrapper.like("REGULAR_CONTENT", ("\"" + examItem + "\""));
            }
        }
        queryWrapper.orderByAsc("SORT_NO");
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public DictScheduleRegularDef selectRegularDefById(DictScheduleRegularDefDto dto) {
        QueryWrapper<DictScheduleRegularDef> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(dto.getExamClass())) {
            queryWrapper.eq("EXAM_CLASS", dto.getExamClass());
        }
        if (StringUtils.isNotBlank(dto.getRegularId())) {
            queryWrapper.eq("REGULAR_ID", dto.getRegularId());
        }
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 从JSON字符串构建成 RuleDto 对象
     * @param dto
     * @return
     */
    @Override
    public JsonResult getRegularDefInfo(DictScheduleRegularDefDto dto) {
        if (StringUtils.isBlank(dto.getRegularId())) {
            return JsonResultUtil.failure("规则ID不能为空");
        }
        DictScheduleRegularDef dictScheduleRegularDef = selectRegularDefById(dto);
        if (dictScheduleRegularDef == null) {
            return JsonResultUtil.failure("没有这个[" + dto.getRegularId() + "]规则数据");
        }
        String regularContent = dictScheduleRegularDef.getRegularContent();
        if (StringUtils.isNotBlank(regularContent)) {
            RuleDto ruleDto = JsonUtil.toBean(regularContent, RuleDto.class);
            ruleDto.setExamClass(dictScheduleRegularDef.getExamClass());
            ruleDto.setRegularId(dictScheduleRegularDef.getRegularId());
            ruleDto.setRegularName(dictScheduleRegularDef.getRegularName());
            ruleDto.setRegularMemo(dictScheduleRegularDef.getRegularMemo());
            ruleDto.setSortNo(dictScheduleRegularDef.getSortNo());
            ruleDto.setExcludeFlag(dictScheduleRegularDef.getExcludeFlag());
            commonRegularInfo(dto, ruleDto);
            if (ruleDto.getExamItem() != null && CollectionUtils.isNotEmpty(ruleDto.getExamItem().getValue())) {
                String queryConditionSql = getString2Sql("ITEM_CODE", ruleDto.getExamItem().getValue());
                DictExamItemDto dictExamItemDto = new DictExamItemDto();
                dictExamItemDto.setExamClass(dictScheduleRegularDef.getExamClass());
                dictExamItemDto.setQueryCondition(queryConditionSql);
                List<DictExamItemDto> dictExamItemDtoList = dictExamItemMapper.selectItemListForRegular(dictExamItemDto);
                List<DictExamItemDto> itemDtoList = new ArrayList<>();
                for (DictExamItemDto examItem : dictExamItemDtoList) {
                    DictExamItemDto itemDto = new DictExamItemDto();
                    itemDto.setItemCode(examItem.getItemCode());
                    itemDto.setItemName(examItem.getItemName());
                    if (ruleDto.getSpecialItem() != null && CollectionUtils.isNotEmpty(ruleDto.getSpecialItem().getValue())) {
                        RuleDto.LimitScope specialScope = ruleDto.getSpecialItem();
                        if (CollectionUtils.isNotEmpty(specialScope.getValue())
                                && specialScope.getValue().contains(examItem.getItemCode())) {
                            itemDto.setIsSpecial(Boolean.TRUE);
                        }
                    }
                    if (ruleDto.getSpecialSingleItem() != null
                            && CollectionUtils.isNotEmpty(ruleDto.getSpecialSingleItem().getValue())) {
                        RuleDto.LimitScope specialScope = ruleDto.getSpecialSingleItem();
                        if (CollectionUtils.isNotEmpty(specialScope.getValue())
                                && specialScope.getValue().contains(examItem.getItemCode())) {
                            itemDto.setIsSingleSpecial(Boolean.TRUE);
                        }
                    }
                    if (ruleDto.getSpecialMultiItem() != null
                            && CollectionUtils.isNotEmpty(ruleDto.getSpecialMultiItem().getValue())) {
                        RuleDto.LimitScope specialScope = ruleDto.getSpecialMultiItem();
                        if (CollectionUtils.isNotEmpty(specialScope.getValue())
                                && specialScope.getValue().contains(examItem.getItemCode())) {
                            itemDto.setIsMultiSpecial(Boolean.TRUE);
                        }
                    }
                    itemDtoList.add(itemDto);
                }
                ruleDto.setDictExamItemList(itemDtoList);
            }
            if (ruleDto.getItemPackage() != null && CollectionUtils.isNotEmpty(ruleDto.getItemPackage().getValue())) {
                QueryWrapper<DictItemGroup> itemGroupQueryWrapper = new QueryWrapper<>();
                itemGroupQueryWrapper.eq("GROUP_TYPE", "2");
                itemGroupQueryWrapper.in("GROUP_CODE", ruleDto.getItemPackage().getValue());
                List<DictItemGroup> itemGroups = dictItemGroupMapper.selectList(itemGroupQueryWrapper);
                List<DictExamItemDto> itemDtoList2 = new ArrayList<>();
                for (DictItemGroup itemGroup : itemGroups) {
                    DictExamItemDto itemDto2 = new DictExamItemDto();
                    itemDto2.setItemCode(itemGroup.getGroupCode());
                    itemDto2.setItemName(itemGroup.getGroupName());
                    itemDto2.setIsPackage(Boolean.TRUE);
                    // 标记为特殊
                    if (ruleDto.getSpecialItem() != null) {
                        RuleDto.LimitScope specialScope2 = ruleDto.getSpecialItem();
                        if (CollectionUtils.isNotEmpty(specialScope2.getValue())
                                && specialScope2.getValue().contains(itemGroup.getGroupCode())) {
                            itemDto2.setIsSpecial(Boolean.TRUE);
                        }
                    }
                    // 标记为单个特殊
                    if (ruleDto.getSpecialSingleItem() != null
                            && CollectionUtils.isNotEmpty(ruleDto.getSpecialSingleItem().getValue())) {
                        RuleDto.LimitScope specialScope = ruleDto.getSpecialSingleItem();
                        if (CollectionUtils.isNotEmpty(specialScope.getValue())
                                && specialScope.getValue().contains(itemGroup.getGroupCode())) {
                            itemDto2.setIsSingleSpecial(Boolean.TRUE);
                        }
                    }
                    // 标记为多个特殊
                    if (ruleDto.getSpecialMultiItem() != null
                            && CollectionUtils.isNotEmpty(ruleDto.getSpecialMultiItem().getValue())) {
                        RuleDto.LimitScope specialScope = ruleDto.getSpecialMultiItem();
                        if (CollectionUtils.isNotEmpty(specialScope.getValue())
                                && specialScope.getValue().contains(itemGroup.getGroupCode())) {
                            itemDto2.setIsMultiSpecial(Boolean.TRUE);
                        }
                    }
                    itemDtoList2.add(itemDto2);
                }
                if (ruleDto.getDictExamItemList() != null) {
                    itemDtoList2.addAll(ruleDto.getDictExamItemList());
                }
                ruleDto.setDictExamItemList(itemDtoList2);
            }
            List<String> specialOnlyDoList = new ArrayList<>();
            List<String> specialNoDoList = new ArrayList<>();
            if (StringUtils.isNotBlank(ruleDto.getVip())) {
                if ("1".equals(ruleDto.getVip())) {
                    specialOnlyDoList.add(ConstantsUtil.RegularAttribute.VIP.getKey());
                } else {
                    specialNoDoList.add(ConstantsUtil.RegularAttribute.VIP.getKey());
                }
            }
            if (StringUtils.isNotBlank(ruleDto.getClinicPath())) {
                if ("1".equals(ruleDto.getClinicPath())) {
                    specialOnlyDoList.add(ConstantsUtil.RegularAttribute.CLINIC_PATH.getKey());
                } else {
                    specialNoDoList.add(ConstantsUtil.RegularAttribute.CLINIC_PATH.getKey());
                }
            }
            if (StringUtils.isNotBlank(ruleDto.getBedSide())) {
                if ("1".equals(ruleDto.getBedSide())) {
                    specialOnlyDoList.add(ConstantsUtil.RegularAttribute.BED_SIDE.getKey());
                } else {
                    specialNoDoList.add(ConstantsUtil.RegularAttribute.BED_SIDE.getKey());
                }
            }
            if (StringUtils.isNotBlank(ruleDto.getIndolence())) {
                if ("1".equals(ruleDto.getIndolence())) {
                    specialOnlyDoList.add(ConstantsUtil.RegularAttribute.INDOLENCE.getKey());
                } else {
                    specialNoDoList.add(ConstantsUtil.RegularAttribute.INDOLENCE.getKey());
                }
            }
            if (StringUtils.isNotBlank(ruleDto.getCriticallyIll())) {
                if ("1".equals(ruleDto.getCriticallyIll())) {
                    specialOnlyDoList.add(ConstantsUtil.RegularAttribute.CRITICALLY_ILL.getKey());
                } else {
                    specialNoDoList.add(ConstantsUtil.RegularAttribute.CRITICALLY_ILL.getKey());
                }
            }
            if (StringUtils.isNotBlank(ruleDto.getCreateDoc())) {
                if ("1".equals(ruleDto.getCreateDoc())) {
                    specialOnlyDoList.add(ConstantsUtil.RegularAttribute.CREATE_DOC.getKey());
                } else {
                    specialNoDoList.add(ConstantsUtil.RegularAttribute.CREATE_DOC.getKey());
                }
            }
            if (StringUtils.isNotBlank(ruleDto.getInfectious())) {
                if ("1".equals(ruleDto.getInfectious())) {
                    specialOnlyDoList.add(ConstantsUtil.RegularAttribute.INFECTIOUS.getKey());
                } else {
                    specialNoDoList.add(ConstantsUtil.RegularAttribute.INFECTIOUS.getKey());
                }
            }
            if (StringUtils.isNotBlank(ruleDto.getMultiDrug())) {
                if ("1".equals(ruleDto.getMultiDrug())) {
                    specialOnlyDoList.add(ConstantsUtil.RegularAttribute.MULTI_DRUG.getKey());
                } else {
                    specialNoDoList.add(ConstantsUtil.RegularAttribute.MULTI_DRUG.getKey());
                }
            }
            if (StringUtils.isNotBlank(ruleDto.getNeedToCalm())) {
                if ("1".equals(ruleDto.getNeedToCalm())) {
                    specialOnlyDoList.add(ConstantsUtil.RegularAttribute.NEED_TO_CALM.getKey());
                } else {
                    specialNoDoList.add(ConstantsUtil.RegularAttribute.NEED_TO_CALM.getKey());
                }
            }
            RuleDto.SpecialProperty specialProperty = new RuleDto.SpecialProperty();
            specialProperty.setOnlyDoList(specialOnlyDoList);
            specialProperty.setNoDoList(specialNoDoList);
            ruleDto.setSpecialProperty(specialProperty);
            List<String> itemOnlyDoList = new ArrayList<>();
            List<String> itemNoDoList = new ArrayList<>();
            if (StringUtils.isNotBlank(ruleDto.getEnhance())) {
                if ("1".equals(ruleDto.getEnhance())) {
                    itemOnlyDoList.add(ConstantsUtil.RegularAttribute.EN_CHANCE.getKey());
                } else {
                    itemNoDoList.add(ConstantsUtil.RegularAttribute.EN_CHANCE.getKey());
                }
            }
            if (StringUtils.isNotBlank(ruleDto.getCalm())) {
                if ("1".equals(ruleDto.getCalm())) {
                    itemOnlyDoList.add(ConstantsUtil.RegularAttribute.CALM.getKey());
                } else {
                    itemNoDoList.add(ConstantsUtil.RegularAttribute.CALM.getKey());
                }
            }
            if (StringUtils.isNotBlank(ruleDto.getEmptyStomach())) {
                if ("1".equals(ruleDto.getEmptyStomach())) {
                    itemOnlyDoList.add(ConstantsUtil.RegularAttribute.EMPTY_STOMACH.getKey());
                } else {
                    itemNoDoList.add(ConstantsUtil.RegularAttribute.EMPTY_STOMACH.getKey());
                }
            }
            if (StringUtils.isNotBlank(ruleDto.getBernao())) {
                if ("1".equals(ruleDto.getBernao())) {
                    itemOnlyDoList.add(ConstantsUtil.RegularAttribute.BER_NAO.getKey());
                } else {
                    itemNoDoList.add(ConstantsUtil.RegularAttribute.BER_NAO.getKey());
                }
            }
            if (StringUtils.isNotBlank(ruleDto.getPuncture())) {
                if ("1".equals(ruleDto.getPuncture())) {
                    itemOnlyDoList.add(ConstantsUtil.RegularAttribute.PUNCTURE.getKey());
                } else {
                    itemNoDoList.add(ConstantsUtil.RegularAttribute.PUNCTURE.getKey());
                }
            }
            RuleDto.ItemProperty itemProperty = new RuleDto.ItemProperty();
            itemProperty.setOnlyDoList(itemOnlyDoList);
            itemProperty.setNoDoList(itemNoDoList);
            ruleDto.setItemProperty(itemProperty);
            if (ruleDto.getAge() != null) {
                RuleDto.AgeScope ageScope = new RuleDto.AgeScope();
                List<String> ageScopeList = new ArrayList<>();
                if (CollectionUtils.isNotEmpty(ruleDto.getAge().getAgeStrList())) {
                    ageScopeList.addAll(ruleDto.getAge().getAgeStrList());
                } else if (CollectionUtils.isNotEmpty(ruleDto.getAge().getDayScope())) {
                    for (RuleDto.DayScope dayScope : ruleDto.getAge().getDayScope()) {
                        String ageScopeStr = DateUtil.day2Age(dayScope.getMin()) + "~" + DateUtil.day2Age(dayScope.getMax());
                        ageScopeList.add(ageScopeStr);
                    }
                }
                ageScope.setGrant(ruleDto.getAge().getGrant());
                ageScope.setAgeScopeList(ageScopeList);
                ruleDto.setAge(ageScope);
            }
            if (ruleDto.getGestationalWeek() != null) {
                RuleDto.GestationalWeekScope gestationalWeekScope = new RuleDto.GestationalWeekScope();
                if (CollectionUtils.isNotEmpty(ruleDto.getGestationalWeek().getGestationalWeekStrList())) {
                    gestationalWeekScope.setGestationalWeekScopeList(ruleDto.getGestationalWeek().getGestationalWeekStrList());
                }
                gestationalWeekScope.setGrant(ruleDto.getGestationalWeek().getGrant());
                ruleDto.setGestationalWeek(gestationalWeekScope);
            }
            return JsonResultUtil.success("成功", ruleDto);
        }
        return JsonResultUtil.failure("该[" + dto.getRegularId() + "]规则没有设置规则内容");
    }

    @Override
    public JsonResult delRegularDef(DictScheduleRegularDefDto dto) {
        if (StringUtils.isBlank(dto.getRegularId())) {
            return JsonResultUtil.failure("规则ID不能为空");
        }
        DictScheduleRegularDef regularDefDto = selectRegularDefById(dto);
        if (regularDefDto == null) {
            return JsonResultUtil.failure("没有这条[" + dto.getRegularId() + "]规则数据");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("EXAM_CLASS", dto.getExamClass());
        map.put("REGULAR_ID", dto.getRegularId());
        int result = baseMapper.deleteByMap(map);
        if (result > 0) {
            DictScheduleApmDto scheduleApmDto = new DictScheduleApmDto();
            scheduleApmDto.setExamClass(regularDefDto.getExamClass());
            scheduleApmDto.setRegularId(regularDefDto.getRegularId());
            scheduleApmDto.setRegularName(regularDefDto.getRegularName());
            scheduleApmDto.setRegularContent(regularDefDto.getRegularContent());
            examSyslogService.saveExamSyslogForDesc(ConstantsUtil.ModuleName.DICT_SCHEDULE_REGULAR_DEF.name(), ConstantsUtil.OperateName.DELETE.getDesc(), scheduleApmDto);
            cacheServiceImpl.clearRegularCache(dto.getRegularId());
            return JsonResultUtil.success("删除成功");
        }
        return JsonResultUtil.failure("删除失败");
    }

    /**
     * 保存预约规则
     *
     * @param dto
     * @return
     */
    @Override
    public JsonResult saveRegularDef(DictScheduleRegularDefDto dto) {
        DictUsersDto dictUsers = commonService.dictUsers(new ExamApplyDto());
        String userDeptCode = "";
        if (dictUsers != null) {
            userDeptCode = dictUsers.getDeptCode();
        }
        String regularId = getRegularId(0);
        dto.setRegularId(regularId);

        DictScheduleRegularDef dictScheduleRegularDef = selectRegularDefById(dto);
        if (dictScheduleRegularDef != null) {
            return JsonResultUtil.failure("已存在这条[" + dto.getRegularId() + "]规则数据");
        }

        DictScheduleRegularDef regularDef = new DictScheduleRegularDef();
        regularDef.setRegularId(regularId);
        regularDef.setExamClass(dto.getExamClass());
        regularDef.setRegularName(dto.getRegularName());
        regularDef.setRegularMemo(dto.getRegularMemo());
        regularDef.setDeptCode(userDeptCode);
        String regularContent = "";
        if (ConstantsUtil.RegularModule.REGULAR_SCHEDULE.getKey().equals(dto.getRegularModule())) {
            regularContent = transContent4Schedule(dto);
        } else if (ConstantsUtil.RegularModule.REGULAR_NUMBER.getKey().equals(dto.getRegularModule())) {
            regularContent = transContent4Number(dto);
        }
        regularDef.setRegularContent(regularContent);
        regularDef.setSortNo(dto.getSortNo());
        regularDef.setExcludeFlag(dto.getExcludeFlag());
        regularDef.setRegularType(dto.getRegularType());
        int result = baseMapper.insert(regularDef);
        if (result > 0) {
            DictScheduleApmDto scheduleApmDto = new DictScheduleApmDto();
            scheduleApmDto.setExamClass(regularDef.getExamClass());
            scheduleApmDto.setRegularId(regularDef.getRegularId());
            scheduleApmDto.setRegularName(regularDef.getRegularName());
            scheduleApmDto.setRegularContent(regularDef.getRegularContent());
            scheduleApmDto.setExcludeFlag(regularDef.getExcludeFlag());
            examSyslogService.saveExamSyslogForDesc(ConstantsUtil.ModuleName.DICT_SCHEDULE_REGULAR_DEF.name(), ConstantsUtil.OperateName.INSERT.getDesc(), scheduleApmDto);
            return JsonResultUtil.success("新增成功");
        }
        return JsonResultUtil.failure("新增失败");
    }

    /**
     * 生成新的regularId
     *
     * @param n 重试次数
     * @return
     */
    private String getRegularId(int n) {
        // 生成新的regularId
        String regularId = dictSerialService.getSerialId("SCHEDULE_REGULAR_ID");
        // 判断regularId 存在就递归调用直到重试n次
        QueryWrapper<DictScheduleRegularDef> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("REGULAR_ID", regularId);
        if (n < 30 && baseMapper.selectCount(queryWrapper) > 0) {
            ++n;
            return getRegularId(n);
        }
        return regularId;
    }

    @Override
    public JsonResult editRegularDef(DictScheduleRegularDefDto dto) {
        if (StringUtils.isBlank(dto.getRegularId())) {
            return JsonResultUtil.failure("规则ID不能为空");
        }
        DictScheduleRegularDef dictScheduleRegularDef = selectRegularDefById(dto);
        if (dictScheduleRegularDef == null) {
            return JsonResultUtil.failure("不存在这条[" + dto.getRegularId() + "]规则数据");
        }
        DictScheduleRegularDef regularDef = new DictScheduleRegularDef();
        regularDef.setRegularId(dto.getRegularId());
        regularDef.setExamClass(dto.getExamClass());
        regularDef.setRegularName(dto.getRegularName());
        regularDef.setRegularMemo(dto.getRegularMemo());
        String regularContent = "";
        if (ConstantsUtil.RegularModule.REGULAR_SCHEDULE.getKey().equals(dto.getRegularModule())) {
            regularContent = transContent4Schedule(dto);
        } else if (ConstantsUtil.RegularModule.REGULAR_NUMBER.getKey().equals(dto.getRegularModule())) {
            regularContent = transContent4Number(dto);
        }
        regularDef.setRegularContent(regularContent);
        regularDef.setSortNo(dto.getSortNo());
        regularDef.setExcludeFlag(dto.getExcludeFlag());
        regularDef.setRegularType(dto.getRegularType());
        QueryWrapper<DictScheduleRegularDef> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("EXAM_CLASS", dto.getExamClass());
        queryWrapper.eq("REGULAR_ID", dto.getRegularId());
        int result = baseMapper.update(regularDef, queryWrapper);
        if (result > 0) {
            DictScheduleApmDto scheduleApmDto = new DictScheduleApmDto();
            scheduleApmDto.setExamClass(regularDef.getExamClass());
            scheduleApmDto.setRegularId(regularDef.getRegularId());
            scheduleApmDto.setRegularName(regularDef.getRegularName());
            scheduleApmDto.setRegularContent(regularDef.getRegularContent());
            scheduleApmDto.setExcludeFlag(regularDef.getExcludeFlag());
            examSyslogService.saveExamSyslogForDesc(ConstantsUtil.ModuleName.DICT_SCHEDULE_REGULAR_DEF.name(), ConstantsUtil.OperateName.UPDATE.getDesc(), scheduleApmDto);
            EhCacheUtil.removeForCacheName(ConstantsUtil.EhCacheName.regularCache.name());
            EhCacheUtil.removeForCacheName(ConstantsUtil.EhCacheName.ruleResultCache.name());
            return JsonResultUtil.success("修改成功");
        }
        return JsonResultUtil.failure("修改失败");
    }

    /**
     * 预约规则生成 构建JSON字符串
     *
     * @param dto
     * @return
     */
    private String transContent4Schedule(DictScheduleRegularDefDto dto) {
        RuleDto ruleDto = new RuleDto();
        if (StringUtils.isNotBlank(dto.getPriorityOrders())) {
            RuleDto.LimitScope priorityScope = new RuleDto.LimitScope();
            priorityScope.setGrant(StringUtils.isNotBlank(dto.getIsPriorityOrder()) ? dto.getIsPriorityOrder() : "1");
            priorityScope.setValue(CommonUtil.split2List(dto.getPriorityOrders()));
            ruleDto.setPriorityOrder(priorityScope);
        }
        if (StringUtils.isNotBlank(dto.getWards())) {
            RuleDto.LimitScope wardScope = new RuleDto.LimitScope();
            wardScope.setGrant(StringUtils.isNotBlank(dto.getIsWard()) ? dto.getIsWard() : "1");
            wardScope.setValue(CommonUtil.split2List(dto.getWards()));
            ruleDto.setWard(wardScope);
        }
        if (StringUtils.isNotBlank(dto.getDepts())) {
            RuleDto.LimitScope deptScope = new RuleDto.LimitScope();
            deptScope.setGrant(StringUtils.isNotBlank(dto.getIsDept()) ? dto.getIsDept() : "1");
            deptScope.setValue(CommonUtil.split2List(dto.getDepts()));
            ruleDto.setDept(deptScope);
        }
        if (StringUtils.isNotBlank(dto.getPatientSources())) {
            RuleDto.LimitScope sourceScope = new RuleDto.LimitScope();
            sourceScope.setGrant(StringUtils.isNotBlank(dto.getIsPatientSource()) ? dto.getIsPatientSource() : "1");
            sourceScope.setValue(CommonUtil.split2List(dto.getPatientSources()));
            ruleDto.setPatientSource(sourceScope);
        }
        if (StringUtils.isNotBlank(dto.getSexs())) {
            RuleDto.LimitScope sexScope = new RuleDto.LimitScope();
            sexScope.setGrant(StringUtils.isNotBlank(dto.getIsSex()) ? dto.getIsSex() : "1");
            sexScope.setValue(CommonUtil.split2List(dto.getSexs()));
            ruleDto.setSex(sexScope);
        }
        if (StringUtils.isNotBlank(dto.getTransTools())) {
            RuleDto.LimitScope toolScope = new RuleDto.LimitScope();
            toolScope.setGrant(StringUtils.isNotBlank(dto.getIsTransTool()) ? dto.getIsTransTool() : "1");
            toolScope.setValue(CommonUtil.split2List(dto.getTransTools()));
            ruleDto.setTransTool(toolScope);
        }
        if (StringUtils.isNotBlank(dto.getSpecialOnlyDoes())) {
            List<String> onlyDoList = CommonUtil.split2List(dto.getSpecialOnlyDoes());
            for (String onlyDo : onlyDoList) {
                if (ConstantsUtil.RegularAttribute.VIP.getKey().equals(onlyDo)) {
                    ruleDto.setVip("1");
                } else if (ConstantsUtil.RegularAttribute.CLINIC_PATH.getKey().equals(onlyDo)) {
                    ruleDto.setClinicPath("1");
                } else if (ConstantsUtil.RegularAttribute.BED_SIDE.getKey().equals(onlyDo)) {
                    ruleDto.setBedSide("1");
                } else if (ConstantsUtil.RegularAttribute.INDOLENCE.getKey().equals(onlyDo)) {
                    ruleDto.setIndolence("1");
                } else if (ConstantsUtil.RegularAttribute.CRITICALLY_ILL.getKey().equals(onlyDo)) {
                    ruleDto.setCriticallyIll("1");
                } else if (ConstantsUtil.RegularAttribute.CREATE_DOC.getKey().equals(onlyDo)) {
                    ruleDto.setCreateDoc("1");
                } else if (ConstantsUtil.RegularAttribute.INFECTIOUS.getKey().equals(onlyDo)) {
                    ruleDto.setInfectious("1");
                } else if (ConstantsUtil.RegularAttribute.MULTI_DRUG.getKey().equals(onlyDo)) {
                    ruleDto.setMultiDrug("1");
                } else {
                    if (!ConstantsUtil.RegularAttribute.NEED_TO_CALM.getKey().equals(onlyDo)) {
                        continue;
                    }
                    ruleDto.setNeedToCalm("1");
                }
            }
        }
        if (StringUtils.isNotBlank(dto.getSpecialNoDoes())) {
            List<String> noDoList = CommonUtil.split2List(dto.getSpecialNoDoes());
            for (String noDo : noDoList) {
                if (ConstantsUtil.RegularAttribute.VIP.getKey().equals(noDo)) {
                    ruleDto.setVip("0");
                } else if (ConstantsUtil.RegularAttribute.CLINIC_PATH.getKey().equals(noDo)) {
                    ruleDto.setClinicPath("0");
                } else if (ConstantsUtil.RegularAttribute.BED_SIDE.getKey().equals(noDo)) {
                    ruleDto.setBedSide("0");
                } else if (ConstantsUtil.RegularAttribute.INDOLENCE.getKey().equals(noDo)) {
                    ruleDto.setIndolence("2");
                } else if (ConstantsUtil.RegularAttribute.CRITICALLY_ILL.getKey().equals(noDo)) {
                    ruleDto.setCriticallyIll("0");
                } else if (ConstantsUtil.RegularAttribute.CREATE_DOC.getKey().equals(noDo)) {
                    ruleDto.setCreateDoc("0");
                } else if (ConstantsUtil.RegularAttribute.INFECTIOUS.getKey().equals(noDo)) {
                    ruleDto.setInfectious("0");
                } else if (ConstantsUtil.RegularAttribute.MULTI_DRUG.getKey().equals(noDo)) {
                    ruleDto.setMultiDrug("0");
                } else {
                    if (!ConstantsUtil.RegularAttribute.NEED_TO_CALM.getKey().equals(noDo)) {
                        continue;
                    }
                    ruleDto.setNeedToCalm("0");
                }
            }
        }
        if (StringUtils.isNotBlank(dto.getItemFlagOnlyDoes())) {
            List<String> onlyDoList = CommonUtil.split2List(dto.getItemFlagOnlyDoes());
            for (String onlyDo : onlyDoList) {
                if (ConstantsUtil.RegularAttribute.EN_CHANCE.getKey().equals(onlyDo)) {
                    ruleDto.setEnhance("1");
                } else if (ConstantsUtil.RegularAttribute.CALM.getKey().equals(onlyDo)) {
                    ruleDto.setCalm("1");
                } else if (ConstantsUtil.RegularAttribute.EMPTY_STOMACH.getKey().equals(onlyDo)) {
                    ruleDto.setEmptyStomach("1");
                } else if (ConstantsUtil.RegularAttribute.BER_NAO.getKey().equals(onlyDo)) {
                    ruleDto.setBernao("1");
                } else {
                    if (!ConstantsUtil.RegularAttribute.PUNCTURE.getKey().equals(onlyDo)) {
                        continue;
                    }
                    ruleDto.setPuncture("1");
                }
            }
        }
        if (StringUtils.isNotBlank(dto.getItemFlagNoDoes())) {
            List<String> noDoList = CommonUtil.split2List(dto.getItemFlagNoDoes());
            for (String noDo : noDoList) {
                if (ConstantsUtil.RegularAttribute.EN_CHANCE.getKey().equals(noDo)) {
                    ruleDto.setEnhance("0");
                } else if (ConstantsUtil.RegularAttribute.CALM.getKey().equals(noDo)) {
                    ruleDto.setCalm("0");
                } else if (ConstantsUtil.RegularAttribute.EMPTY_STOMACH.getKey().equals(noDo)) {
                    ruleDto.setEmptyStomach("0");
                } else if (ConstantsUtil.RegularAttribute.BER_NAO.getKey().equals(noDo)) {
                    ruleDto.setBernao("0");
                } else {
                    if (!ConstantsUtil.RegularAttribute.PUNCTURE.getKey().equals(noDo)) {
                        continue;
                    }
                    ruleDto.setPuncture("0");
                }
            }
        }
        if (StringUtils.isNotBlank(dto.getExamItems())) {
            RuleDto.LimitScope itemScope = new RuleDto.LimitScope();
            itemScope.setGrant("1");
            itemScope.setValue(CommonUtil.split2List(dto.getExamItems()));
            ruleDto.setExamItem(itemScope);
        }
        if (StringUtils.isNotBlank(dto.getItemPackages())) {
            RuleDto.LimitScope packageScope = new RuleDto.LimitScope();
            packageScope.setGrant("1");
            packageScope.setValue(CommonUtil.split2List(dto.getItemPackages()));
            ruleDto.setItemPackage(packageScope);
        }
        if (StringUtils.isNotBlank(dto.getSpecialItems())) {
            RuleDto.LimitScope specialScope = new RuleDto.LimitScope();
            specialScope.setValue(CommonUtil.split2List(dto.getSpecialItems()));
            ruleDto.setSpecialItem(specialScope);
        }
        // 标记为特殊单项目
        if (StringUtils.isNotBlank(dto.getSpecialSingleItems())) {
            RuleDto.LimitScope specialScope = new RuleDto.LimitScope();
            specialScope.setValue(CommonUtil.split2List(dto.getSpecialSingleItems()));
            ruleDto.setSpecialSingleItem(specialScope);
        }
        // 标记为特殊多项目
        if (StringUtils.isNotBlank(dto.getSpecialMultiItems())) {
            RuleDto.LimitScope specialScope = new RuleDto.LimitScope();
            specialScope.setValue(CommonUtil.split2List(dto.getSpecialMultiItems()));
            ruleDto.setSpecialMultiItem(specialScope);
        }
        if (StringUtils.isNotBlank(dto.getAgeScopes())) {
            RuleDto.AgeScope ageScope = new RuleDto.AgeScope();
            ageScope.setGrant(StringUtils.isNotBlank(dto.getIsAge()) ? dto.getIsAge() : "1");
            List<RuleDto.DayScope> dayScopeList = new ArrayList<>();
            List<String> ageScopeList = CommonUtil.split2List(dto.getAgeScopes());
            for (String age : ageScopeList) {
                String[] ageArr = age.split("~");
                int min = 0;
                if (StringUtils.isNotBlank(ageArr[0])) {
                    min = DateUtil.util2Day(ageArr[0]);
                }
                int max = 0;
                if (StringUtils.isNotBlank(ageArr[1])) {
                    max = DateUtil.util2Day(ageArr[1]);
                }
                RuleDto.DayScope dayScope = new RuleDto.DayScope();
                dayScope.setMin(min);
                dayScope.setMax(max);
                dayScopeList.add(dayScope);
            }
            ageScope.setDayScope(dayScopeList);
            ageScope.setAgeStrList(ageScopeList);
            ruleDto.setAge(ageScope);
        }
        if (StringUtils.isNotBlank(dto.getReqPhysicians())) {
            RuleDto.LimitScope reqPhysician = new RuleDto.LimitScope();
            reqPhysician.setGrant(StringUtils.isNotBlank(dto.getIsReqPhysician()) ? dto.getIsReqPhysician() : "1");
            reqPhysician.setValue(CommonUtil.split2List(dto.getReqPhysicians()));
            ruleDto.setReqPhysician(reqPhysician);
        }
        if (StringUtils.isNotBlank(dto.getDiagnosticKeywords())) {
            RuleDto.LimitScope diagnosticKeyword = new RuleDto.LimitScope();
            diagnosticKeyword.setGrant(StringUtils.isNotBlank(dto.getIsDiagnosticKeyword()) ? dto.getIsDiagnosticKeyword() : "1");
            diagnosticKeyword.setValue(CommonUtil.split2List(dto.getDiagnosticKeywords()));
            ruleDto.setDiagnosticKeyword(diagnosticKeyword);
        }
        if (StringUtils.isNotBlank(dto.getReqDayScope())) {
            RuleDto.NumScope reqDayScope = new RuleDto.NumScope();
            reqDayScope.setGrant(StringUtils.isNotBlank(dto.getIsReqDay()) ? dto.getIsReqDay() : "1");
            String[] reqDayArr = dto.getReqDayScope().split("-");
            if (StringUtils.isNotBlank(reqDayArr[0]) && !"空".equals(reqDayArr[0])) {
                reqDayScope.setMin(Integer.parseInt(reqDayArr[0]));
            }
            if (StringUtils.isNotBlank(reqDayArr[1]) && !"空".equals(reqDayArr[1])) {
                reqDayScope.setMax(Integer.parseInt(reqDayArr[1]));
            }
            ruleDto.setReqDayScope(reqDayScope);
        }
        if (StringUtils.isNotBlank(dto.getTerminalTypes())) {
            RuleDto.LimitScope terminalType = new RuleDto.LimitScope();
            terminalType.setGrant(StringUtils.isNotBlank(dto.getIsTerminalType()) ? dto.getIsTerminalType() : "1");
            terminalType.setValue(CommonUtil.split2List(dto.getTerminalTypes()));
            ruleDto.setTerminalType(terminalType);
        }
        if (StringUtils.isNotBlank(dto.getGestationalWeekScopes())) {
            RuleDto.GestationalWeekScope gestationalWeekScope = new RuleDto.GestationalWeekScope();
            gestationalWeekScope.setGrant(StringUtils.isNotBlank(dto.getIsGestationalWeek()) ? dto.getIsGestationalWeek() : "1");
            List<RuleDto.DayScope> dayScopeList = new ArrayList<>();
            List<String> gestationalWeekStrList = new ArrayList<>();
            List<String> gestationalWeekList = CommonUtil.split2List(dto.getGestationalWeekScopes());
            for (String gestationalWeek : gestationalWeekList) {
                String gestationalWeekStr = gestationalWeek.replaceAll("-", "~");
                String[] gestationalWeekArr = gestationalWeekStr.split("~");
                int min2 = 0;
                if (StringUtils.isNotBlank(gestationalWeekArr[0])) {
                    min2 = DateUtil.util2Day(gestationalWeekArr[0]);
                }
                int max2 = 0;
                if (StringUtils.isNotBlank(gestationalWeekArr[1])) {
                    max2 = DateUtil.util2Day(gestationalWeekArr[1]);
                }
                RuleDto.DayScope dayScope2 = new RuleDto.DayScope();
                dayScope2.setMin(min2);
                dayScope2.setMax(max2);
                dayScopeList.add(dayScope2);
                gestationalWeekStrList.add(gestationalWeekStr);
            }
            gestationalWeekScope.setDayScope(dayScopeList);
            gestationalWeekScope.setGestationalWeekStrList(gestationalWeekStrList);
            ruleDto.setGestationalWeek(gestationalWeekScope);
        }
        if (StringUtils.isNotBlank(dto.getNurseUnits())) {
            RuleDto.LimitScope nurseUnitScope = new RuleDto.LimitScope();
            nurseUnitScope.setGrant(StringUtils.isNotBlank(dto.getIsNurseUnit()) ? dto.getIsNurseUnit() : "1");
            nurseUnitScope.setValue(CommonUtil.split2List(dto.getNurseUnits()));
            ruleDto.setNurseUnit(nurseUnitScope);
        }
        if (StringUtils.isNotBlank(dto.getItemCountScope())) {
            RuleDto.NumScope itemCountScope = new RuleDto.NumScope();
            itemCountScope.setGrant(StringUtils.isNotBlank(dto.getIsItemCount()) ? dto.getIsItemCount() : "1");
            String[] itemCountArr = dto.getItemCountScope().split("-");
            if (StringUtils.isNotBlank(itemCountArr[0]) && !"空".equals(itemCountArr[0])) {
                itemCountScope.setMin(Integer.parseInt(itemCountArr[0]));
            }
            if (StringUtils.isNotBlank(itemCountArr[1]) && !"空".equals(itemCountArr[1])) {
                itemCountScope.setMax(Integer.parseInt(itemCountArr[1]));
            }
            ruleDto.setItemCountScope(itemCountScope);
        }
        return JsonUtil.toJson(ruleDto);
    }

    private String transContent4Number(DictScheduleRegularDefDto dto) {
        RuleDto ruleDto = new RuleDto();
        if (StringUtils.isNotBlank(dto.getWards())) {
            RuleDto.LimitScope wardScope = new RuleDto.LimitScope();
            wardScope.setGrant("1");
            wardScope.setValue(CommonUtil.split2List(dto.getWards()));
            ruleDto.setWard(wardScope);
        }
        if (StringUtils.isNotBlank(dto.getDepts())) {
            RuleDto.LimitScope deptScope = new RuleDto.LimitScope();
            deptScope.setGrant("1");
            deptScope.setValue(CommonUtil.split2List(dto.getDepts()));
            ruleDto.setDept(deptScope);
        }
        if (StringUtils.isNotBlank(dto.getPatientSources())) {
            RuleDto.LimitScope sourceScope = new RuleDto.LimitScope();
            sourceScope.setGrant("1");
            sourceScope.setValue(CommonUtil.split2List(dto.getPatientSources()));
            ruleDto.setPatientSource(sourceScope);
        }
        if (StringUtils.isNotBlank(dto.getPriorityOrders())) {
            RuleDto.LimitScope priorityScope = new RuleDto.LimitScope();
            priorityScope.setGrant("1");
            priorityScope.setValue(CommonUtil.split2List(dto.getPriorityOrders()));
            ruleDto.setPriorityOrder(priorityScope);
        }
        if (StringUtils.isNotBlank(dto.getPatientAttributes())) {
            ruleDto.setPatientAttributes(CommonUtil.split2List(dto.getPatientAttributes()));
        }
        if (StringUtils.isNotBlank(dto.getTerminalTypes())) {
            ruleDto.setTerminalTypes(CommonUtil.split2List(dto.getTerminalTypes()));
        }
        if (StringUtils.isNotBlank(dto.getAgeScopes())) {
            RuleDto.AgeScope ageScope = new RuleDto.AgeScope();
            ageScope.setGrant("1");
            List<RuleDto.DayScope> dayScopeList = new ArrayList<>();
            List<String> ageScopeList = CommonUtil.split2List(dto.getAgeScopes());
            for (String age : ageScopeList) {
                String[] ageArr = age.split("~");
                int min = 0;
                if (StringUtils.isNotBlank(ageArr[0])) {
                    min = DateUtil.util2Day(ageArr[0]);
                }
                int max = 0;
                if (StringUtils.isNotBlank(ageArr[1])) {
                    max = DateUtil.util2Day(ageArr[1]);
                }
                RuleDto.DayScope dayScope = new RuleDto.DayScope();
                dayScope.setMin(min);
                dayScope.setMax(max);
                dayScopeList.add(dayScope);
            }
            ageScope.setDayScope(dayScopeList);
            ageScope.setAgeStrList(ageScopeList);
            ruleDto.setAge(ageScope);
        }
        if (StringUtils.isNotBlank(dto.getExamItems())) {
            RuleDto.LimitScope itemScope = new RuleDto.LimitScope();
            itemScope.setGrant("1");
            itemScope.setValue(CommonUtil.split2List(dto.getExamItems()));
            ruleDto.setExamItem(itemScope);
        }
        if (StringUtils.isNotBlank(dto.getItemPackages())) {
            RuleDto.LimitScope packageScope = new RuleDto.LimitScope();
            packageScope.setGrant("1");
            packageScope.setValue(CommonUtil.split2List(dto.getItemPackages()));
            ruleDto.setItemPackage(packageScope);
        }
        if (StringUtils.isNotBlank(dto.getNumScope())) {
            RuleDto.NumScope numScope = new RuleDto.NumScope();
            String numScopeStr = "空" + dto.getNumScope() + "空";
            String[] numArr = numScopeStr.split("-");
            int min2 = (StringUtils.isNotBlank(numArr[0]) && !"空".equals(numArr[0])) ? Integer.parseInt(numArr[0].replaceAll("空", "")) : 0;
            int max2 = (StringUtils.isNotBlank(numArr[1]) && !"空".equals(numArr[1])) ? Integer.parseInt(numArr[1].replaceAll("空", "")) : 0;
            numScope.setMin(min2);
            numScope.setMax(max2);
            ruleDto.setNumScope(numScope);
        }
        if (StringUtils.isNotBlank(dto.getReqDayScope())) {
            RuleDto.NumScope reqDayScope = new RuleDto.NumScope();
            reqDayScope.setGrant("1");
            String[] reqDayArr = dto.getReqDayScope().split("-");
            if (StringUtils.isNotBlank(reqDayArr[0]) && !"空".equals(reqDayArr[0])) {
                reqDayScope.setMin(Integer.parseInt(reqDayArr[0]));
            }
            if (StringUtils.isNotBlank(reqDayArr[1]) && !"空".equals(reqDayArr[1])) {
                reqDayScope.setMax(Integer.parseInt(reqDayArr[1]));
            }
            ruleDto.setReqDayScope(reqDayScope);
        }
        if (StringUtils.isNotBlank(dto.getGestationalWeekScopes())) {
            RuleDto.GestationalWeekScope gestationalWeekScope = new RuleDto.GestationalWeekScope();
            gestationalWeekScope.setGrant("1");
            List<RuleDto.DayScope> dayScopeList = new ArrayList<>();
            List<String> gestationalWeekStrList = new ArrayList<>();
            List<String> gestationalWeekList = CommonUtil.split2List(dto.getGestationalWeekScopes());
            for (String gestationalWeek : gestationalWeekList) {
                String gestationalWeekStr = gestationalWeek.replaceAll("-", "~");
                String[] gestationalWeekArr = gestationalWeekStr.split("~");
                int min3 = 0;
                if (StringUtils.isNotBlank(gestationalWeekArr[0])) {
                    min3 = DateUtil.util2Day(gestationalWeekArr[0]);
                }
                int max3 = 0;
                if (StringUtils.isNotBlank(gestationalWeekArr[1])) {
                    max3 = DateUtil.util2Day(gestationalWeekArr[1]);
                }
                RuleDto.DayScope dayScope2 = new RuleDto.DayScope();
                dayScope2.setMin(min3);
                dayScope2.setMax(max3);
                dayScopeList.add(dayScope2);
                gestationalWeekStrList.add(gestationalWeekStr);
            }
            gestationalWeekScope.setDayScope(dayScopeList);
            gestationalWeekScope.setGestationalWeekStrList(gestationalWeekStrList);
            ruleDto.setGestationalWeek(gestationalWeekScope);
        }
        if (StringUtils.isNotBlank(dto.getNurseUnits())) {
            RuleDto.LimitScope nurseUnitScope = new RuleDto.LimitScope();
            nurseUnitScope.setGrant("1");
            nurseUnitScope.setValue(CommonUtil.split2List(dto.getNurseUnits()));
            ruleDto.setNurseUnit(nurseUnitScope);
        }
        if (StringUtils.isNotBlank(dto.getItemCountScope())) {
            RuleDto.NumScope itemCountScope = new RuleDto.NumScope();
            itemCountScope.setGrant("1");
            String[] itemCountArr = dto.getItemCountScope().split("-");
            if (StringUtils.isNotBlank(itemCountArr[0]) && !"空".equals(itemCountArr[0])) {
                itemCountScope.setMin(Integer.parseInt(itemCountArr[0]));
            }
            if (StringUtils.isNotBlank(itemCountArr[1]) && !"空".equals(itemCountArr[1])) {
                itemCountScope.setMax(Integer.parseInt(itemCountArr[1]));
            }
            ruleDto.setItemCountScope(itemCountScope);
        }
        return JsonUtil.toJson(ruleDto);
    }

    /**
     * 获取规则设置初始化数据
     *
     * @param dto
     * @return
     */
    @Override
    public RuleDto getInitRegularCommonInfo(DictScheduleRegularDefDto dto) {
        RuleDto ruleDto = new RuleDto();
        commonRegularInfo(dto, ruleDto);
        return ruleDto;
    }

    private void commonRegularInfo(DictScheduleRegularDefDto dto, RuleDto ruleDto) {
        //
        ruleDto.setDictQueueClassList(dictQueueClassService.getList(new DictQueueClassDto()));
        ruleDto.setDictWardList(dictWardService.getListAll());

        // 申请科室
        DictDeptDto dictDeptDto = new DictDeptDto();
        dictDeptDto.setClinicAttr("0");
        ruleDto.setDictDeptList(dictDeptService.getList(dictDeptDto));
        ruleDto.setDictPatientSourceList(dictPatientSourceService.getListAll());
        ruleDto.setTransToolList(configService.getTransTools());

        List<RuleDto.ComboBox> patientAttriList = getPatientAttriList();
        ruleDto.setPatientAttributeList(patientAttriList);

        List<RuleDto.ComboBox> terminalTypeList = getTerminalTypeList();
        ruleDto.setTerminalTypeList(terminalTypeList);
        ruleDto.setDictUsersList(dictUsersService.getList(new DictUsersDto()));

        // 诊断关键字
        String diagnosticKeywordStr = configService.getConfigByName(ConstantsUtil.ConfigName.DIAGNOSTIC_KEYWORD.getKey());
        if (StringUtils.isNotBlank(diagnosticKeywordStr)) {
            List<ConfigDto.DiagnosticKeyword> diagnosticKeywordList = JsonUtil.toList(diagnosticKeywordStr, ConfigDto.DiagnosticKeyword.class);
            if (CollectionUtils.isNotEmpty(diagnosticKeywordList)) {
                List<String> keywordList = new ArrayList<>();
                if (StringUtils.isNotBlank(dto.getExamClass())) {
                    List<String> keywrods = diagnosticKeywordList.stream()
                            .filter(x -> CollectionUtils.isNotEmpty(x.getExamClass()) && x.getExamClass().contains(dto.getExamClass()))
                            .map(x -> x.getKeyword())
                            .flatMap(Collection::stream)
                            .collect(Collectors.toList());
                    keywordList.addAll(keywrods);

//                    for (ConfigDto.DiagnosticKeyword diagnosticKeywordDto : diagnosticKeywordList) {
//                        List<String> examClassList = diagnosticKeywordDto.getExamClass();
//                        if (examClassList != null && examClassList.contains(dto.getExamClass())) {
//                            keywordList.addAll(diagnosticKeywordDto.getKeyword());
//                        }
//                    }
                } else {
                    List<String> keywrods = diagnosticKeywordList.stream()
                            .filter(x -> CollectionUtils.isNotEmpty(x.getExamClass()))
                            .map(x -> x.getKeyword())
                            .flatMap(Collection::stream)
                            .collect(Collectors.toList());
                    keywordList.addAll(keywrods);

//                    for (ConfigDto.DiagnosticKeyword diagnosticKeywordDto : diagnosticKeywordList) {
//                        List<String> examClassList = diagnosticKeywordDto.getExamClass();
//                        if (examClassList != null) {
//                            keywordList.addAll(diagnosticKeywordDto.getKeyword());
//                        }
//                    }
                }
                ruleDto.setDiagnosticKeywordList(keywordList);
            }
        }
        ruleDto.setNurseUnitList(dictDeptService.getNurseUnit());
    }

    /**
     * 构造终端列表信息
     *
     * @return
     */
    private static List<RuleDto.ComboBox> getTerminalTypeList() {
        List<RuleDto.ComboBox> terminalTypeList = new ArrayList<>();
        RuleDto.ComboBox dept = new RuleDto.ComboBox();
        dept.setText("医技");
        dept.setValue(ConstantsUtil.TerminalType.DEPT.getType());
        terminalTypeList.add(dept);
        RuleDto.ComboBox clinic = new RuleDto.ComboBox();
        clinic.setText("临床");
        clinic.setValue(ConstantsUtil.TerminalType.CLINIC_IN.getType());
        terminalTypeList.add(clinic);
        RuleDto.ComboBox self = new RuleDto.ComboBox();
        self.setText("自助机");
        self.setValue(ConstantsUtil.TerminalType.SELF.getType());
        terminalTypeList.add(self);
        RuleDto.ComboBox mobile = new RuleDto.ComboBox();
        mobile.setText("移动端");
        mobile.setValue(ConstantsUtil.TerminalType.MOBILE.getType());
        terminalTypeList.add(mobile);
        RuleDto.ComboBox scheduleCenter = new RuleDto.ComboBox();
        scheduleCenter.setText("预约中心");
        scheduleCenter.setValue(ConstantsUtil.TerminalType.SCHEDULE_CENTER.getType());
        terminalTypeList.add(scheduleCenter);
        RuleDto.ComboBox scheduleManage = new RuleDto.ComboBox();
        scheduleManage.setText("预约管理");
        scheduleManage.setValue(ConstantsUtil.TerminalType.SCHEDULE_MANAGE.getType());
        terminalTypeList.add(scheduleManage);
        return terminalTypeList;
    }

    /**
     * 够着患者属性列表信息
     *
     * @return
     */
    private static List<RuleDto.ComboBox> getPatientAttriList() {
        List<RuleDto.ComboBox> patientAttriList = new ArrayList<>();
        RuleDto.ComboBox vip = new RuleDto.ComboBox();
        vip.setText(ConstantsUtil.RegularAttribute.VIP.getValue());
        vip.setValue(ConstantsUtil.RegularAttribute.VIP.getKey());
        patientAttriList.add(vip);
        RuleDto.ComboBox clinicPath = new RuleDto.ComboBox();
        clinicPath.setText(ConstantsUtil.RegularAttribute.CLINIC_PATH.getValue());
        clinicPath.setValue(ConstantsUtil.RegularAttribute.CLINIC_PATH.getKey());
        patientAttriList.add(clinicPath);
        RuleDto.ComboBox bedSide = new RuleDto.ComboBox();
        bedSide.setText(ConstantsUtil.RegularAttribute.BED_SIDE.getValue());
        bedSide.setValue(ConstantsUtil.RegularAttribute.BED_SIDE.getKey());
        patientAttriList.add(bedSide);
        RuleDto.ComboBox indolence = new RuleDto.ComboBox();
        indolence.setText(ConstantsUtil.RegularAttribute.INDOLENCE.getValue());
        indolence.setValue(ConstantsUtil.RegularAttribute.INDOLENCE.getKey());
        patientAttriList.add(indolence);
        RuleDto.ComboBox criticallyIll = new RuleDto.ComboBox();
        criticallyIll.setText(ConstantsUtil.RegularAttribute.CRITICALLY_ILL.getValue());
        criticallyIll.setValue(ConstantsUtil.RegularAttribute.CRITICALLY_ILL.getKey());
        patientAttriList.add(criticallyIll);
        RuleDto.ComboBox createDoc = new RuleDto.ComboBox();
        createDoc.setText(ConstantsUtil.RegularAttribute.CREATE_DOC.getValue());
        createDoc.setValue(ConstantsUtil.RegularAttribute.CREATE_DOC.getKey());
        patientAttriList.add(createDoc);
        RuleDto.ComboBox infectious = new RuleDto.ComboBox();
        infectious.setText(ConstantsUtil.RegularAttribute.INFECTIOUS.getValue());
        infectious.setValue(ConstantsUtil.RegularAttribute.INFECTIOUS.getKey());
        patientAttriList.add(infectious);
        RuleDto.ComboBox multiDrug = new RuleDto.ComboBox();
        multiDrug.setText(ConstantsUtil.RegularAttribute.MULTI_DRUG.getValue());
        multiDrug.setValue(ConstantsUtil.RegularAttribute.MULTI_DRUG.getKey());
        patientAttriList.add(multiDrug);
        return patientAttriList;
    }

    private String getString2Sql(String id, List<String> list) {
        StringBuffer sb = new StringBuffer();
        String returnString = "";
        if (CollectionUtils.isEmpty(list)) {
            sb.append(id).append("=''");
        } else {
            for (int i = 0; i < list.size(); ++i) {
                if (i == 0) {
                    sb.append(id);
                    sb.append(" in (");
                }
                sb.append("'");
                sb.append(list.get(i));
                sb.append("'");
                if (i >= 900 && i < list.size() - 1) {
                    if (i % 900 == 0) {
                        sb.append(") or ");
                        sb.append(id);
                        sb.append(" in (");
                    } else {
                        sb.append(",");
                    }
                } else if (i < list.size() - 1) {
                    sb.append(",");
                }
                if (i == list.size() - 1) {
                    sb.append(")");
                }
            }
        }
        returnString = sb.toString();
        return returnString;
    }
}
